# GNAFU - "Ground, Navy and Air Fuck-Up" real-time strategy game
# Copyright (C) 2008-2009 k0wax <k0waxk0wax@gmail.com>
#
# This file is part of GNAFU.
#
# GNAFU is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# GNAFU is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GNAFU.  If not, see <http://www.gnu.org/licenses/>.

"""Field class and other routines"""
from __future__ import division, absolute_import
from math import *
from array import array
from src import xtypes, geom, conf
from src import views, vars
from .views import *

# surface types
surface_types = xtypes.enumtype('SurfaceTypes', 'land sea transitional air')
surface_minmax_levels = {
    'land': (4, 7), surface_types.land: (4, 7), # fixme
    'sea': (0, 3), surface_types.sea: (0, 3),
}

@views.has_init_view
@views.addview({'init_view': field_init_view, 'draw': field_draw}) # post init -> schedule initialization after models
class Field(object):
    def __init__(self, w=10, h=10):
        self.w, self.h = w, h
        self.w_px, self.h_px = self.w * vars.tile_size, self.h * vars.tile_size
        self.zlevel = [] # 2d array
        vars.field_w = w
        vars.field_h = h
        self._generate_zlevel()
        self.init_view() #XXX bug. should be inited by game's view manager XXX should be inited per-instance
    def _generate_zlevel(self):
        from src.util import noise
        noise_data = noise.create_layered_data(w=self.w, h=self.h, scale=16)
        for x, y, y_trig in self.cloop(y_trig=True):
            if y_trig:
                self.zlevel.append(array('B', []))
            idx = noise_data[y*self.w + x] # downward
            self.zlevel[y].append(idx)
    def __setstate__(self, state):
        self.__dict__.update(state)
        self.init_view()
    def cloop(self, y_trig=False, y_cb=None, post_cb=None):
        """Coords loop"""
        kw_y_trig = y_trig # ns conflict
        y_trig = False
        for y in xrange(self.h):
            y_trig = True
            if y_cb: y_cb[0](*y_cb[1:])
            for x in xrange(self.w):
                yield (x, y) if not kw_y_trig else (x, y, y_trig)
                y_trig = False
            if post_cb: post_cb[0](*post_cb[1:])
